﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;

namespace TCCT_CTC_CSDLDangVienV1.DanhMuc
{
    public partial class frmUserList : frmBase
    {
        private string Action = MyConst.ACTION.Insert;
        public string SelectedID = string.Empty;

        public frmUserList()
        {
            InitializeComponent();
        }



        private static frmUserList _instance = null;
        public static frmUserList Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                    _instance = new frmUserList();
                return _instance;
            }
            set { _instance = value; }
        }

        private void frmUserList_Load(object sender, EventArgs e)
        {
            try
            {

                ApplyUI();

                Permision();

                if (!gTimKiemThongTin.Enabled) return;

                BindDataToControl();

                BindDataToGrid();
                frmUserList.Instance = this;
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nơi gán thuộc tính giao diện cho các control
        private void ApplyUI()
        {
            UI.Button.ApplyInsert(btnThemMoi);
            UI.Button.ApplyUpdate(btnSuaDoi);


            UI.Button.ApplyClose(btnThoat);

            UI.Button.ApplyExportExcel(btnXuatExcel);


            UI.TextBox.ApplyFind(txtHoTenFind);


            UI.Grid.ApplyDefault(dgData);

            this.MainGridView.Columns["CreateDate"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.MainGridView.Columns["CreateDate"].DisplayFormat.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;
            this.MainGridView.Columns["UpdateDate"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.MainGridView.Columns["UpdateDate"].DisplayFormat.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;


        }

        //Kiểm tra xem user đang đăng nhập có quyền xem, thêm, sửa, xóa hay không?
        private void Permision()
        {
            try
            {
                if (MyCommon.CurrentUserIsAdministrator || MyCommon.CurrentUserIsAdmin) return;
                MyCommon.ShowDialogMessage("Bạn không có quyền truy cập mục này. Mọi cố gắng truy cập của bạn là vi phạm");
                gTimKiemThongTin.Enabled = false;
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nơi tải dữ liệu danh mục lên các control để lựa chọn: ví dụ: Combobox, listbox ...
        private void BindDataToControl()
        {
            try
            {

            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nơi tải dữ liệu lên grid chứa dữ liệu
        private void BindDataToGrid()
        {
            try
            {
                DataTable temdt = SqlHelper.ExecuteDataTable(CommandType.Text, "Select * from tblDau_Moi Where ID='" + MyCommon.CurrentUserDauMoiID + "' ");

                string sql = "Select U.*, DM.TenDV, (Select Top 1 IsNull(HoTen,'') As HoTen From tblUser U1 Where ID=U.UserID And DauMoiID=U.DauMoi_ID) As NguoiTao " +
                          "From tblUser U " + 
                          "Inner Join tblDau_Moi DM On DM.ID=U.DauMoiID " +
                          "Where U.Username<>'Administrator' And DM.CapTren Like '%" + temdt.Rows[0]["CapTren"].ToString() + "%' " +
                          "Order By DM.TenDV, U.HoTen ";

                dgData.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sql);

            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {

                DanhMuc.frmUserUpdate ff = new frmUserUpdate();
                if (!MyCommon.CurrentUserIsAdministrator)
                {
                    ff.SelectedDauMoiID = MyCommon.CurrentUserDauMoiID;
                    ff.txtDauMoi.Visible = false;
                    ff.chkIsAdmin.Enabled = false;

                }
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sCurentID = SqlHelper.ExecuteScalar(MyTran, CommandType.Text, "Select CurentID From tblDau_Moi Where ID='" + ff.SelectedDauMoiID + "'").ToString();

                    string sql = "Insert Into tblUser(ID, UserName, Password, HoTen, MoTa, DauMoiID, IsAdmin, IsLocked, UserID, DauMoi_ID, CreateDate) Values(@ID, @UserName, @Password, @HoTen, @MoTa, @DauMoiID, @IsAdmin, @IsLocked, @UserID, @DauMoi_ID, GetDate()); ";

                    sql += "Update tblDau_Moi Set CurentID=CurentID+1 Where ID ='" + ff.SelectedDauMoiID + "'; ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    int iCurentID = Util.ToInt(sCurentID) + 1;
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.BigInt, ParameterDirection.Input, iCurentID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Username", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtUsername.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Password", SqlDbType.NVarChar, ParameterDirection.Input, EncryptSMSB.Encrypt(ff.txtPassword.Text.Trim())));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@HoTen", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtHoTen.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtMoTa.Text));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoiID", SqlDbType.BigInt, ParameterDirection.Input, ff.SelectedDauMoiID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@IsAdmin", SqlDbType.Bit, ParameterDirection.Input, ff.chkIsAdmin.Checked));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@IsLocked", SqlDbType.Bit, ParameterDirection.Input, ff.chkIsLocked.Checked));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoi_ID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserDauMoiID));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }

        private void btnSuaDoi_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgData.MainView.RowCount == 0)
                {
                    ShowInfoMessage("Không có dữ liệu để sửa thông tin");
                    return;
                }

                frmUserUpdate ff = new frmUserUpdate(); 

                ff.SelectedDauMoiID = GetString(dgData, "DauMoiID");

                DataTable temDT = SqlHelper.ExecuteDataTable(CommandType.Text, "Select * From tblUser Where ID='" + GetString(dgData, "ID") + "' And DauMoiID='" + ff.SelectedDauMoiID + "' ");

                ff.txtUsername.Text = temDT.Rows[0]["Username"].ToString();
                ff.txtPassword.Text = EncryptSMSB.Decrypt(temDT.Rows[0]["Password"].ToString());
                ff.txtNhapLaiPassword.Text = ff.txtPassword.Text;
                ff.txtHoTen.Text = temDT.Rows[0]["HoTen"].ToString();
                ff.txtMoTa.Text = temDT.Rows[0]["MoTa"].ToString();
                ff.txtDauMoi.Visible = false;
                ff.lblDauMoi.Visible = false;
                ff.chkIsAdmin.Checked = Util.ToBool(temDT.Rows[0]["IsAdmin"].ToString());
                ff.chkIsLocked.Checked = Util.ToBool(temDT.Rows[0]["IsLocked"].ToString());
                if (!MyCommon.CurrentUserIsAdministrator)
                {
                    ff.chkIsAdmin.Enabled = false;
                    if (ff.chkIsAdmin.Checked) ff.chkIsLocked.Enabled = false;
                }
                ff.txtUsername.Focus();
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Update tblUser Set  UserName=@UserName, Password=@Password, HoTen=@HoTen, "+
                        "MoTa=@MoTa, IsAdmin=@IsAdmin, IsLocked=@IsLocked, UserID=@UserID, DauMoi_ID=@DauMoi_ID, UpdateDate=GetDate() Where ID=@ID And DauMoiID=@DauMoiID; ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.BigInt, ParameterDirection.Input, GetString(dgData, "ID")));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Username", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtUsername.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@Password", SqlDbType.NVarChar, ParameterDirection.Input, EncryptSMSB.Encrypt(ff.txtPassword.Text.Trim())));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@HoTen", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtHoTen.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtMoTa.Text));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoiID", SqlDbType.BigInt, ParameterDirection.Input, ff.SelectedDauMoiID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@IsAdmin", SqlDbType.Bit, ParameterDirection.Input, ff.chkIsAdmin.Checked));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@IsLocked", SqlDbType.Bit, ParameterDirection.Input, ff.chkIsLocked.Checked));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoi_ID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserDauMoiID));

                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);
                    BindDataToGrid();
                }


            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }



     
        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                ((DataTable)dgData.DataSource).DefaultView.RowFilter = "HoTen Like '%" + txtHoTenFind.Text.Trim() + "%' Or TeDV Like '%" + txtHoTenFind.Text.Trim() + "%' ";
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Down)
                    dgData.Focus();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }



        //Nếu phím là enter và Action=Find thì có nghĩa là chấp nhận kết quả tìm kiếm.
        private void dgData_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

            }
        }

        private void menuThemMoi_Click(object sender, EventArgs e)
        {
            if (btnThemMoi.Enabled)
                btnThemMoi_Click(null, null);
        }

        private void menuSuaDoi_Click(object sender, EventArgs e)
        {
            if (btnSuaDoi.Enabled)
                btnSuaDoi_Click(null, null);
        }




        private void menuTimKiem_Click(object sender, EventArgs e)
        {
            ResetValues(gTimKiemThongTin);
            txtHoTenFind.Focus();
        }



        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            try
            {
                ExportToExcel(dgData);
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }








    }
}